package com.zdxlz.fcmp.common.core.util;

import com.zdxlz.fcmp.common.core.constant.CommonConstants;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @className HmacUtil
 * @description
 * @author: aman
 * @date 2025/2/1 20:20
 */
public class HmacUtil {

    /**
     * 使用给定的密钥生成输入数据的HMAC-SHA256签名。
     *
     * @param data   要签名的数据
     * @param secret 密钥
     * @return 签名后的字符串（Base64编码）
     * @throws Exception 如果加密过程出错
     */
    public static String generateHmacSha256(String data, String secret) {
        try {
            Mac hmac = Mac.getInstance(CommonConstants.HMAC_SHA256_ALGORITHM);
            byte[] secretBytes = Base64.getDecoder().decode(secret);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretBytes, CommonConstants.HMAC_SHA256_ALGORITHM);
            hmac.init(secretKeySpec);
            byte[] hash = hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
}
